using Masuit.Tools;
using Simple.Contracts.Contracts;
using Simple.Contracts.Models;
using Simple.Contracts.Models.Common;
using Simple.Repository;
using Simple.Repository.SimpleEntitys;
using static FreeSql.Internal.GlobalFilter;

namespace Simple.Services.Services
{
    /// <summary>
    /// 照护计划模板服务实现
    /// </summary>
    public class CarePlanTemplateService : BaseService, ICarePlanTemplateService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fsql">FreeSQL实例</param>
        /// <param name="mapper">AutoMapper实例</param>
        public CarePlanTemplateService(FreeSqlCloud freeSqlCloud, CurrentAccount currentAccount) : base(freeSqlCloud, currentAccount) { }

        /// <summary>
        /// 保存照护计划模板
        /// </summary>
        /// <param name="model">保存参数</param>
        /// <returns>模板Id</returns>
        public async Task<Result<long>> SaveCarePlanTemplateAsync(SaveCarePlanTemplateInput input)
        {
            // 保存计划模板
            long carePlanTemplateId = 0;
            if (input.Id.HasValue)
            {
                // 更新操作
                var template = await _simpleFreeSql.Select<CarePlanTemplate>().Where(t => t.Id == input.Id.Value && t.IsDelete == 0 && t.CompanyId == _currentAccount.CompanyId).FirstAsync();
                if (template == null)
                {
                    return Result<long>.FriendlyReminder("当前编辑的模板不存在或已被删除，请刷新重试");
                }

                template.Name = input.Name;
                template.PersonalizedCareNeeds = input.PersonalizedCareNeeds;
                template.Sort = input.Sort;
                template.UpdateTime = System.DateTime.Now;
                template.UpdateBy = _currentAccount.EmployeeId;

                await _simpleFreeSql.Update<CarePlanTemplate>().SetSource(template).ExecuteAffrowsAsync();
                carePlanTemplateId = template.Id;
            }
            else
            {
                // 新增操作
                var template = new CarePlanTemplate
                {
                    Name = input.Name,
                    PersonalizedCareNeeds = input.PersonalizedCareNeeds,
                    CompanyId = _currentAccount.CompanyId,
                    CreateTime = System.DateTime.Now,
                    CreateBy = _currentAccount.EmployeeId,
                    UpdateTime = System.DateTime.Now,
                    UpdateBy = _currentAccount.CompanyId,
                    Sort = input.Sort,
                    IsDelete = 0
                };

                carePlanTemplateId = await _simpleFreeSql.Insert<CarePlanTemplate>(template).ExecuteIdentityAsync();
            }

            // 保存模板任务明细
            if (input.MissionList != null && input.MissionList.Any())
            {
                foreach (var item in input.MissionList)
                {
                    var entity = await _simpleFreeSql.Select<CarePlanTemplateMission>()
                        .Where(x => x.Id == item.Id && x.CompanyId == _currentAccount.CompanyId && x.CarePlanTemplateId == carePlanTemplateId)
                        .FirstAsync();
                    if (entity == null)
                    {
                        if (item.IsDelete == 1)
                        {
                            continue;
                        }
                        entity = new CarePlanTemplateMission()
                        {
                            CarePlanTemplateId = carePlanTemplateId,
                            Name = item.Name,
                            Description = item.Description,
                            CategorizeId = item.CategorizeId,
                            CareMissionId = item.CareMissionId,
                            CreateBy = _currentAccount.EmployeeId,
                            CompanyId = _currentAccount.CompanyId,
                            CreateTime = DateTime.Now,
                            DailyMissionEndTime = item.DailyMissionEndTime,
                            DailyMissionEndTimeValue = item.DailyMissionEndTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionEndTime!.Replace(":", "")),
                            DailyMissionExecutionCount = item.DailyMissionExecutionCount,
                            DailyMissionStartTime = item.DailyMissionStartTime,
                            DailyMissionStartTimeValue = item.DailyMissionStartTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionStartTime!.Replace(":", "")),
                            IsDailyMission = item.IsDailyMission,
                            IsDelete = 0,
                            Sort = item.Sort,
                            UpdateBy = _currentAccount.EmployeeId,
                            UpdateTime = DateTime.Now,
                        };
                        await _simpleFreeSql.Insert<CarePlanTemplateMission>(entity).ExecuteAffrowsAsync();
                    }
                    else
                    {
                        entity.Name = item.Name;
                        entity.Description = item.Description;
                        entity.IsDailyMission = item.IsDailyMission;
                        entity.DailyMissionStartTime = item.DailyMissionStartTime;
                        entity.DailyMissionStartTimeValue = item.DailyMissionStartTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionStartTime!.Replace(":", ""));
                        entity.DailyMissionEndTime = item.DailyMissionEndTime;
                        entity.DailyMissionEndTimeValue = item.DailyMissionEndTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionEndTime!.Replace(":", ""));
                        entity.UpdateBy = _currentAccount.EmployeeId;
                        entity.UpdateTime = DateTime.Now;
                        entity.Sort = item.Sort;
                        entity.IsDelete = item.IsDelete;
                        await _simpleFreeSql.Update<CarePlanTemplateMission>().SetSource(entity).ExecuteAffrowsAsync();
                    }
                }
            }

            return Result<long>.Success(carePlanTemplateId);
        }

        /// <summary>
        /// 删除照护计划模板
        /// </summary>
        /// <param name="id">模板Id</param>
        /// <returns>删除结果</returns>
        public async Task<Result<bool>> DeleteCarePlanTemplateAsync(long id)
        {
            // 执行软删除
            await _simpleFreeSql.Update<CarePlanTemplate>()
                .Set(x => x.IsDelete, 1)
                .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                .Set(x => x.UpdateTime, DateTime.Now)
                .Where(x => x.CompanyId == _currentAccount.CompanyId && x.Id == id)
                .ExecuteAffrowsAsync();

            return Result<bool>.Success(true);
        }

        /// <summary>
        /// 获取照护计划模板列表
        /// </summary>
        /// <returns>模板列表</returns>
        public async Task<Result<List<CarePlanTemplateDto>>> GetCarePlanTemplateListAsync()
        {
            var list = await _simpleFreeSql.Select<CarePlanTemplate>()
                .Where(x => (x.CompanyId == 1 || x.CompanyId == _currentAccount.CompanyId) && x.IsDelete == 0)
                .OrderByDescending(x => x.CompanyId)
                .OrderByDescending(x => x.UpdateTime)
                .ToListAsync(x => new CarePlanTemplateDto()
                {
                    CompanyId = x.CompanyId,
                    CreateTime = x.CreateTime,
                    UpdateTime = x.UpdateTime,
                    Id = x.Id,
                    Name = x.Name,
                    PersonalizedCareNeeds = x.PersonalizedCareNeeds,
                    Sort = x.Sort
                });
            return Result<List<CarePlanTemplateDto>>.Success(list);
        }

        /// <summary>
        /// 获取照护计划模板详情
        /// </summary>
        /// <param name="id">模板Id</param>
        /// <returns>模板详情</returns>
        public async Task<Result<CarePlanTemplateDto?>> GetCarePlanTemplateDetailAsync(long id)
        {
            var item = await _simpleFreeSql.Select<CarePlanTemplate>()
               .Where(x => (x.CompanyId == 1 || x.CompanyId == _currentAccount.CompanyId) && x.IsDelete == 0 && x.Id == id)
               .OrderByDescending(x => x.CompanyId)
               .OrderByDescending(x => x.UpdateTime)
               .FirstAsync(x => new CarePlanTemplateDto()
               {
                   CompanyId = x.CompanyId,
                   CreateTime = x.CreateTime,
                   UpdateTime = x.UpdateTime,
                   Id = x.Id,
                   Name = x.Name,
                   PersonalizedCareNeeds = x.PersonalizedCareNeeds,
                   Sort = x.Sort
               });
            if (item != null)
            {
                item.MissionList = await _simpleFreeSql.Select<CarePlanTemplateMission>()
                    .Where(x => x.CompanyId == item.CompanyId && x.CarePlanTemplateId == item.Id && x.IsDelete == 0)
                    .OrderByDescending(x => x.IsDailyMission)
                    .OrderBy(x => x.DailyMissionStartTime)
                    .ToListAsync(x => new CarePlanTemplateMissionDto()
                    {
                        CareMissionId = x.CareMissionId,
                        DailyMissionStartTime = x.DailyMissionStartTime,
                        IsDailyMission = x.IsDailyMission,
                        CategorizeId = x.CategorizeId,
                        DailyMissionEndTime = x.DailyMissionEndTime,
                        DailyMissionExecutionCount = x.DailyMissionExecutionCount,
                        IsDelete = x.IsDelete,
                        Description = x.Description,
                        Id = x.Id,
                        Name = x.Name,
                        Sort = x.Sort,
                        UpdateTime = x.UpdateTime,
                        DailyMissionEndTimeValue = x.DailyMissionEndTimeValue,
                        DailyMissionStartTimeValue = x.DailyMissionStartTimeValue,
                    });
            }
            return Result<CarePlanTemplateDto?>.Success(item);
        }

        /// <summary>
        /// 复制照护计划模板
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Result<long>> CopyCarePlanTemplateAsync(CopyCarePlanTemplateInput input)
        {
            var carePlanTemplate = await _simpleFreeSql.Select<CarePlanTemplate>()
               .Where(x => (x.CompanyId == 1 || x.CompanyId == _currentAccount.CompanyId) && x.Id == input.Id)
               .FirstAsync();
            if (carePlanTemplate == null)
            {
                return Result<long>.FriendlyReminder("当前选择要复制的模板不存在或已被删除，请刷新重试");
            }
            var carePlanTemplateCompanyId = carePlanTemplate.CompanyId;
            var carePlanTemplateId = carePlanTemplate.Id;

            carePlanTemplate.Id = 0;
            carePlanTemplate.Name = input.Name;
            carePlanTemplate.CompanyId = _currentAccount.CompanyId;
            carePlanTemplate.CreateTime = DateTime.Now;
            carePlanTemplate.UpdateTime = DateTime.Now;
            carePlanTemplate.CreateBy = _currentAccount.EmployeeId;
            carePlanTemplate.UpdateBy = _currentAccount.EmployeeId;
            carePlanTemplate.IsDelete = 0;
            var newCarePlanTemplateId = await _simpleFreeSql.Insert<CarePlanTemplate>(carePlanTemplate).ExecuteIdentityAsync();

            var carePlanTemplateMissionList = await _simpleFreeSql.Select<CarePlanTemplateMission>().Where(x => x.CompanyId == carePlanTemplateCompanyId && x.CarePlanTemplateId == carePlanTemplateId && x.IsDelete == 0).ToListAsync();
            foreach (var carePlanTemplateMission in carePlanTemplateMissionList)
            {
                carePlanTemplateMission.Id = 0;
                carePlanTemplateMission.CompanyId = _currentAccount.CompanyId;
                carePlanTemplateMission.CarePlanTemplateId = newCarePlanTemplateId;
                carePlanTemplateMission.CreateBy = _currentAccount.EmployeeId;
                carePlanTemplateMission.UpdateBy = _currentAccount.EmployeeId;
                carePlanTemplateMission.CreateTime = DateTime.Now;
                carePlanTemplateMission.UpdateTime = DateTime.Now;
                carePlanTemplateMission.IsDelete = 0;
            }
            await _simpleFreeSql.Insert<CarePlanTemplateMission>(carePlanTemplateMissionList).ExecuteAffrowsAsync();
            return Result<long>.Success(newCarePlanTemplateId);
        }
    }
}